/* 基金-基金购买页面  path: '/fundbuy'
 * 当传下列参数时，输入框默认显示这只基金：
 * ofcode:'基金代码'  ofname:'基金名称'   entrustBs:'买卖方向’(2：认购，3：申购）
 */
<template>
  <div class="fund-buy common-fun-trade">
    <header-top :option="headerOption"></header-top>
    <div class="wrap">
      <div class="top" :class="{'sub-top':entrustBs == 2}">

        <div class="upper">
          <div class="bef"><span></span>基金代码</div>
          <input type="text" placeholder="请输入基金简拼/基金代码" id="input-ofcode" @input="search" v-focus="isSearch" v-model="inputOfcode"
                 @click.stop.prevent="search"/>
          <i class="iconfont icon-qingkong cancel" @click="clearInputOfcode" v-show="inputOfcode != ''"></i>
          <div class="read" v-if="entrustBs == 2">该基金最低起购金额：1000元</div>
        </div>

        <div class="lower">
          <div class="bef"><span></span>{{entrustBs == 2?'认':'申'}}购金额</div>
          <template v-if="entrustBs == 2">
            <div class="read" v-if="errorBalance == ''">账户可用金额 {{enableBalance}} 元</div>
            <div class="read color-red" v-else>账户可用金额:{{errorBalance}}</div>
          </template>
          <input type="text" placeholder="请输入金额" id="input-price" v-model="inputPrice"
                 @input="filterInputPrice" @click.stop.prevent="disapperQuest" />
          <i class="iconfont icon-qingkong cancel" @click="clearInputPrice" v-show="inputPrice != ''"></i>
          <div class="read" v-if="entrustBs == 2">认购需是1000的整数倍</div>
          <template v-else>
            <div class="read" v-if="errorBalance == ''">账户可用金额 {{enableBalance}} 元</div>
            <div class="read color-red" v-else>账户可用金额:{{errorBalance}}</div>
          </template>
        </div>
      </div>

      <div class="bottom">
        <div class="note">注：模拟基金交易的费率统一为0.4%，在真实操作中费率会根据不同的基金品种、操作有所不同</div>
        <div class="button" :class="{'gray':!enableBuy}" @click.stop.prevent="buyFund">确认购买</div>
      </div>

      <div class="under" v-show="entrustBs==3">
        <my-position @chooseFund="chooseFund"></my-position>
      </div>

    </div>
    <div class="quest" v-show="showQuest" @click.stop.prevent>
      <div class="reat"></div>
      <div class="content">&nbsp;&nbsp;当开放式基金首次发售时，这个时期叫做基金募集期，此时购买基金就是认购。通常这时的认购价位1元/份。</div>
    </div>
    <!-- 弹出层 -->
    <search-list v-show="isSearch" :searchList="searchList" @chooseFund="chooseFund" @closeLayer="cancelSearch"></search-list>
    <fund-commit-modal></fund-commit-modal>
  </div>
</template>
<script>
  import HeaderTop from 'components/HeaderTop'
  import Constant from 'common/constant'
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'
  import CommonUtil from 'common/common.util'
  import SearchList from 'components/fund/SearchList'
  import FundCommitModal from 'components/modal/fund/FundCommitModal'
  import MyPosition from 'components/fund/MyPosition'

  export default {
    data () {
      return {
        headerOption: {
          title: '基金购买',
          leftBtn: Constant.leftBtn.BACK,
          operations: [],
          page:Constant.page.FUND_BUY
        },
        userCode: LocalDAO.getUserCode(),
        ofInfo: {ofcode: '', ofname: ''},//基金信息,购买操作时以ofInfo.ofcode为准
        inputOfcode: '',//基金搜索框的值
        inputPrice: '',//金额输入框的值
        entrustBs: 3, //委托类型: 2基金认购 3基金申购,
        enableBalance: '0.00', //可用资金
        lastNum: '',//价格输入框缓存数,
        isSearch: false,//是否显示搜索列表
        enableBuy: false,//是否能购买
        buying:false,//是否购买中标志，避免重复操作购买
        showQuest:false,//是否显示基金认购说明
        timeschel:'',//延时器
        myPosition: [],
        searchList: [],
        errorPosition: '数据加载中...',//持仓报错、提示信息
        errorBalance: ''//资产报错、提示信息
      }
    },
    components: {
      HeaderTop,
      MyPosition,
      SearchList,
      FundCommitModal
    },
    created: function () {
      this.init();
      this.getBalance();
    },
    watch: {
      inputPrice: 'checkInputPrice'
    },
    methods: {
      //初始化
      init(){
        if (this.$route.query.fundStatus == 0) {
          this.entrustBs = 3;
        }else if(this.$route.query.fundStatus == 1){
          this.entrustBs = 2;
        }
        if (this.entrustBs == 2) {
          this.headerOption.operations.push(Constant.operation.QUESTION)
        } else {
          this.headerOption.operations = _.without(this.headerOption.operations, Constant.operation.QUESTION);
        }
        if (this.$route.query.fundName) {
          this.ofInfo.ofname = this.$route.query.fundName;
        }
        if (this.$route.query.fundCode) {
          this.ofInfo.ofcode = this.$route.query.fundCode;
          this.getFund(this.ofInfo.ofcode,this.ofInfo.ofname)
        }
        this.$root.eventHub.$on('showFundQuest',()=>{ //绑定基金说明显示事件
          this.showQuest = !this.showQuest;
          if(this.showQuest){
            clearTimeout(this.timeschel);
            this.timeschel =setTimeout(()=>{
              this.showQuest = false;
            }, 10000)
          }
        })
      },
      //开始模糊查询
      search(){
        this.disapperQuest();
        if (this.inputOfcode.length > 1) {
          this.isSearch = true;
          RemoteDAO.fundSearch(this.inputOfcode, response => {
            if (response.error == 0) {
              let searchList = response.data.body
              this.searchList = CommonUtil.translateFundsStatus(searchList);
            } else {
              this.$store.dispatch('setTip', {text: response.data});
            }
          })
        } else {
          this.cancelSearch()
        }
      },
      //获取资产
      getBalance(){
        this.errorBalance = ''
        RemoteDAO.callJCL11103(this.userCode, response => {
          if (response.error == 0) {
            this.enableBalance = CommonUtil.toFixed(response.data.body.data[0].enable_balance, 2);
            this.errorBalance = ''
          } else {
            this.enableBalance = 0;
            this.errorBalance = response.data;
          }
        })
      },
      //获取基金信息
      getFund(ofcode,ofname){
        if(ofcode !=this.ofInfo.ofcode){
          this.inputPrice = ''
        }
        if(typeof (ofname)!=='undefined'){
          this.inputOfcode = ofcode + ' ' + ofname;
        }
        let params = {
          client_id: this.userCode,
          ofcode: ofcode,
          start: 0,
          limit: 20
        };
        RemoteDAO.callJCL11165(params, response => {
          if (response.error == 0) {
            if (response.data.body.records.length > 0) {
              this.ofInfo = response.data.body.records[0];
              if (this.ofInfo.ofstatue == 1) { //基金认购期
                this.entrustBs = 2;   //界面认购状态
              } else if (this.ofInfo.ofstatue == 0) { //基金可申购
                this.entrustBs = 3;     //界面申购状态
              }

            } else {
              this.$store.dispatch('setTip', {text: '未查询到该基金信息'});
            }
          } else {
            this.$store.dispatch('setTip', {text: response.data});
          }
        })
      },
      //点击持仓列表或搜索列表的行
      chooseFund(item,from){
        this.disapperQuest();
        this.getFund(item.ofcode,item.ofname)
      },
      //购买基金
      buyFund(){
        this.disapperQuest();
        if (this.enableBuy && !this.buying) {
          this.buying = true;
          let obj = {
            clientId: this.userCode,
            tradeType: this.entrustBs,
            marketCd: 1,
            stockCode: this.ofInfo.ofcode || this.inputOfcode,
            tradePrice: this.inputPrice,
            tradeCount: 1,
            bfollow: 0,
            followClient: '',
            groupId: '',
            gameId: ''
          };
          RemoteDAO.callJCL11116(obj, response => {
            if (response.error == 0) {
              const {body = {}} = response.data
              if (body.status == '0') {
                if (body.entrust_no == 0) {
                  this.$store.dispatch('setTip', {text: body.describe || '委托失败!'})
                  return
                }
                this.$store.dispatch('setModal', {
                  visible: true,
                  entrustBs: this.entrustBs,
                  ofname: this.ofInfo.ofname,
                  entrustAmt: this.inputPrice,
                  modalId: Constant.modal.FUND_COMMIT_MODAL
                });
              } else {
                this.$store.dispatch('setTip', {text: body.describe || '委托失败!'})
              }
            } else {
              this.$store.dispatch('setTip', {text: response.data});
            }
            this.buying = false;
          })
        }
      },
      //取消搜索
      cancelSearch(){
        this.isSearch = false;
        this.searchList = [];
        this.disapperQuest();
      },
      //清空基金搜索框并隐藏搜索列表
      clearInputOfcode(){
        this.inputOfcode = '';
        this.cancelSearch();
      },
      //清空金额框
      clearInputPrice(){
        this.inputPrice = '';
        this.disapperQuest();
      },
      //过滤金额框（非金额符号无法输入）
      filterInputPrice(){
        let inputPrice = this.inputPrice;
        if (isNaN(inputPrice)) {
          inputPrice = inputPrice.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符
          inputPrice = inputPrice.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
          inputPrice = inputPrice.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
          inputPrice = inputPrice.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数点
          this.lastNum = inputPrice.toString();
          this.inputPrice = inputPrice;
        }
        if (inputPrice.indexOf(".") > -1 && inputPrice.substring(inputPrice.indexOf(".") + 3, inputPrice.length).length > 0) {
          inputPrice = inputPrice.substring(0, inputPrice.indexOf(".") + 3);//转为保留两位的数字
          this.lastNum = inputPrice.toString();
          this.inputPrice = inputPrice;
        }
        if (Number(inputPrice) > Number(this.enableBalance).toFixed(2)) { //大于剩余资金则转成上次缓存的值
          this.$store.dispatch('setTip', {text: '你没有那么多资金了'});
          inputPrice = this.lastNum;
          this.inputPrice = inputPrice;
        }
        this.lastNum = inputPrice;//缓存这次的值
      },
      //检测金额
      checkInputPrice(){
        if (this.entrustBs == 2) {
          if (Number(this.inputPrice) >= 1000 && Number(this.inputPrice) % 1000 == 0 && this.inputOfcode != '') {
            this.enableBuy = true
          } else {
            this.enableBuy = false
          }
        } else if (this.entrustBs == 3) {
          if (Number(this.inputPrice) > 0 && this.inputOfcode != '') {
            this.enableBuy = true
          } else {
            this.enableBuy = false
          }
        }
      },
      //基金认购说明消失
      disapperQuest(){
        if(this.showQuest){
          this.showQuest = false;
        }
      }
    },
    directives: {
      focus: {
        inserted: function (el, {value}) {
          if (value) {
            el.focus()
          }
        }
      }
    }
  }
</script>
<style scoped>
  .fund-buy {
    overflow: hidden;
  }

  .wrap .top {
    height: 237px;
    box-sizing: border-box;
    background: #fff;
    padding-top: 16px;
  }
  .wrap .sub-top{
    height: 258px !important;
  }

  .wrap .top .read {
    color: #999999;
    font-size: 12px;
    padding: 0 9px;
    margin: 0 10% 6px;
  }

  .wrap .top input {
    border: 1px solid #999999;
    border-radius: 5px;
    height: 45px;
    text-indent: 8px;
    color: #565656;
    margin-bottom: 8px;
    position: relative;
    padding-right: 33px;
    -webkit-appearance: none;
    width:80%;
    margin-left: 10%;
  }

  .wrap .top #input-ofcode {
    z-index: 1031;
  }

  .wrap .top input::-webkit-input-placeholder { /* WebKit browsers */
    color: #999999;
  }

  .wrap .top input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    color: #999999;
  }

  .wrap .top input::-moz-placeholder { /* Mozilla Firefox 19+ */
    color: #999999;
  }

  .wrap .top input:-ms-input-placeholder { /* Internet Explorer 10+ */
    color: #999999;
  }

  .wrap .bottom {
    width: 100%;
    height: 151px;
    box-sizing: border-box;
    background: #F2F2F2;
    border-top: 1px solid #E6E8E7;
    padding: 26px 10% 0;
  }

  .bef {
    position: relative;
    width: 100%;
    padding: 6px 10%;
    font-size: 15px;
    line-height: 0;
  }

  .bef span {
    background: #33a7f1;
    width: 3px;
    height: 12px;
    border-radius: 2px;
    display: inline-block;
    margin-right: 4px;
    position: relative;
    top: 1px;
  }

  .upper {
    width: 100%;
    margin-bottom: 10px;
  }

  .lower {
    width: 100%;
    margin-bottom: 15px;
  }

  .note {
    color: #999999;
    font-size: 12px;
    padding: 0 9px;
    line-height: 14px;
  }

  .button {
    height: 36px;
    line-height: 36px;
    color: white;
    background-color: #3e7be6;
    text-align: center;
    border-radius: 5px;
    font-size: 16px;
    margin: 18px auto 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button.gray {
    background-color: #999999;
  }

  .under {
    position: absolute;
    left: 0;
    right: 0;
    top: 432px;
    bottom: 0;
    background: #fff;
  }

  .cancel {
    position: relative;
    right: 35px;
    font-size: 24px;
    top: 3px;
  }

  .upper .cancel {
    z-index: 1031;
  }
  .quest{
    position: fixed;
    top:45px;
    right:10px;
    z-index:1032;
    width: 100%;
  }
  .quest .reat{
    width:0;
    height: 0;
    border-left: 10px solid transparent;
    border-right: 10px solid transparent;
    border-bottom: 20px solid rgba(0, 0, 0, 0.6);
    position: absolute;
    right: 5px;
  }
  .quest .content{
    background: rgba(0, 0, 0, 0.6);
    border-radius: 7px;
    display: inline-block;
    color: #FFFFFF;
    padding: 4px;
    position: absolute;
    top: 20px;
    right: 0;
    width: 60%;
  }

  @media screen and (max-height: 666px){
    .under {
      position: static;
      height: 235px;
    }
  }

</style>
